package com.shz;

import jakarta.annotation.Resource;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.model.Media;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.List;

@RestController
public class AIController {
    @Resource
    private OpenAiChatModel openAiChatModel;
    @Resource
    ChatClient chatClient;
    @Resource
    ChatModel chatModel;
    @RequestMapping(value="/ai/chat")
    public String chat(@RequestParam(value = "msg") String msg) {
        return openAiChatModel.call(msg);
    }

    @GetMapping(value="/ai/dangjian")
    public String dangjian(@RequestParam(value = "msg") String msg) {
        return chatClient.prompt().user(msg).call().content();
    }

    public static byte[] image2Bytes(String imageUrl) throws IOException {
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<byte[]> response = restTemplate.getForEntity(imageUrl, byte[].class);
        return response.getBody();
    }
    @GetMapping("/ai/mutil")
    public String mutilModel(@RequestParam(value = "msg", defaultValue="全面分析图表中的数据") String msg,String image) throws IOException {
        byte[] imageData=image2Bytes(image);
        UserMessage userMessage = new UserMessage(msg, List.of(new Media(MimeTypeUtils.IMAGE_PNG, imageData)));
        ChatResponse response= chatModel.call(new Prompt(userMessage, OpenAiChatOptions.builder().withModel(OpenAiApi.ChatModel.GPT_4_O.getValue()).build()));
        return  response.getResult().getOutput().getContent();
    }
    @GetMapping("/ai/test")
    public String test(@RequestParam(value = "msg",defaultValue = "中国有多少个叫张飞的人")String msg){
        OpenAiChatOptions aiChatOptions=OpenAiChatOptions.builder().withFunction("locationNameFunction").withModel(OpenAiApi.ChatModel.GPT_4_TURBO).build();
        ChatResponse response = chatModel.call(new Prompt(msg, aiChatOptions));
        return response.getResult().getOutput().getContent();
    }
}


